import requests
from flask import Flask, request, jsonify

from config import Config
from models import db, User
from utils import decrypt_wx_data

app = Flask(__name__)
app.config.from_object(Config)


@app.route('/api/login', methods=['POST'])
def wx_login():
    code = request.json.get('code')
    if not code:
        return jsonify({'error': 'Missing code'}), 400

    # 调用微信接口获取 openid 和 session_key
    url = f'https://api.weixin.qq.com/sns/jscode2session?appid={app.config["WX_APPID"]}&secret={app.config["WX_SECRET"]}&js_code={code}&grant_type=authorization_code'
    response = requests.get(url)
    data = response.json()

    if 'errcode' in data:
        return jsonify({'error': data['errmsg']}), 400

    openid = data['openid']
    session_key = data['session_key']

    # 保存用户信息到数据库（示例）
    # 这里可以结合数据库存储 openid 和 session_key
    return jsonify({'openid': openid, 'session_key': session_key})


@app.route('/api/get_phone', methods=['POST'])
def get_phone():
    encrypted_data = request.json.get('encryptedData')
    iv = request.json.get('iv')
    session_key = request.json.get('session_key')  # 需从缓存或数据库获取

    try:
        phone_data = decrypt_wx_data(encrypted_data, session_key, iv)
        return jsonify({'phone': phone_data['purePhoneNumber']})
    except Exception as e:
        return jsonify({'error': '解密失败'}), 400


@app.route('/api/save_user', methods=['POST'])
def save_user():
    openid = request.json.get('openid')
    session_key = request.json.get('session_key')
    phone = request.json.get('phone')

    user = User.query.filter_by(openid=openid).first()
    if not user:
        user = User(openid=openid, session_key=session_key, phone=phone)
        db.session.add(user)
    else:
        user.session_key = session_key
        user.phone = phone

    db.session.commit()
    return jsonify({'success': True})
